package com.sqx.modules.health.controller;

import com.sqx.modules.health.common.ApiConsts;
import com.sqx.modules.health.service.ReceiveDataService;
import com.sqx.modules.health.service.ReceivePressureDataService;
import com.sqx.modules.health.utils.HdwDataCheckUtils;
import com.sqx.modules.health.utils.StringUtil;
import com.sqx.modules.health.vo.SrcDataValue;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Calendar;


@Controller
@RequestMapping({ "/receive" })
public class ReceiveDataController {

	@Autowired
	private ReceiveDataService receiveDataService;
	@Autowired
	private ReceivePressureDataService receivePressureDataService;

	/** 服务器IP地址 */
	//private final String currServerIP = "42.236.73.238";
	private final String currServerIP = "101.43.12.150";

	/**
	 * 接收设备数据上报请求 设备数据回调
	 * 
	 * @param request
	 * @param response
	 * @param data
	 * @throws IOException
	 */
	@GetMapping("/saveReceive")
	public void receiveData(HttpServletRequest request,
			HttpServletResponse response, @RequestParam("data") String data)
			throws IOException {
		// 校验数据合法性
		if (checkReceivedData(data)) {
			System.out.println("厂商推送数据");
			System.out.println(data);
			SrcDataValue srcDatavalue = new SrcDataValue(data);

			// 只接收血糖、血压数据!!!!!!!!!!!!!!!!
			if(!(ApiConsts.DataTypeEnum.BLPRESSURE.getCode().equals(srcDatavalue.getDeviceType()) || ApiConsts.DataTypeEnum.BLGLUCOSE.getCode().equals(
					srcDatavalue.getDeviceType()))){
				return;
			}
			boolean isSuccess =false;
			// 处理上报的数据
			if(ApiConsts.DataTypeEnum.BLGLUCOSE.getCode().equals(srcDatavalue.getDeviceType())){
				isSuccess = this.receiveDataService.handleReceivedData(srcDatavalue);
			} else if(ApiConsts.DataTypeEnum.BLPRESSURE.getCode().equals(srcDatavalue.getDeviceType())){
				isSuccess = this.receivePressureDataService.handleReceivedData(srcDatavalue);
			}

			// 给血糖设备回复报文
			if (isSuccess) {
				StringBuilder rslt = new StringBuilder("+IP");
				rslt.append(getServerIp(request));
				rslt.append(getServerDate());
				rslt.append("OK");

				OutputStream outWriter = response.getOutputStream();

				byte[] towrite = rslt.toString().getBytes();

				response.setContentLength(towrite.length);
				outWriter.write(towrite);
				outWriter.flush();
				outWriter.close();
			}
		}
	}

	/**
	 * 校验上报数据的合法性
	 * 
	 * @param data
	 * @return
	 */
	private boolean checkReceivedData(String data) {

		if ((data != null) && ((data.length() == 85) || (data.length() == 87))) {

			if ((data.length() == 85)
					&& (HdwDataCheckUtils.isSumCheckCode(data))) {
				return true;
			}

			if ((data.length() == 87)
					&& (HdwDataCheckUtils.isSumCheckCode(data))
					&& (HdwDataCheckUtils.isCrc8Code(data))) {
				return true;
			}
		}

		return false;
	}

	/**
	 * 获取请求端ip地址
	 * 
	 * @param request
	 * @return
	 */
	private String getServerIp(HttpServletRequest request) {

		String[] ips = StringUtil.toString(currServerIP).split("\\.");

		if ((null == ips) || (0 >= ips.length)) {
			return "";
		}

		String ports = StringUtils.leftPad(
				Integer.toHexString(request.getLocalPort()), 4, "0");

		StringBuilder ipsb = new StringBuilder();

		int sum = 0;

		for (int i = 0; i < ips.length; i++) {
			ipsb.append(StringUtils.leftPad(
					Integer.toHexString(Integer.valueOf(ips[i]).intValue()), 2,
					"0"));
			sum ^= Integer.valueOf(ips[i]).intValue();
		}

		sum ^= Integer.valueOf(ports.substring(2, 4), 16).intValue();
		ipsb.append(ports.substring(2, 4));
		sum ^= Integer.valueOf(ports.substring(0, 2), 16).intValue();
		ipsb.append(ports.substring(0, 2));
		ipsb.append(Integer.toHexString(sum));

		return ipsb.toString().toUpperCase();
	}

	/**
	 * 获取服务器时间
	 * 
	 * @return
	 */
	private String getServerDate() {

		StringBuilder datasb = new StringBuilder();

		int sum = 0;

		Calendar cal = Calendar.getInstance();
		Integer year = Integer.valueOf(cal.get(1) % 100);
		datasb.append(StringUtils.leftPad(Integer.toHexString(year.intValue()),
				2, "0"));
		sum ^= year.intValue();

		Integer month = Integer.valueOf(cal.get(2) + 1);
		datasb.append(StringUtils.leftPad(
				Integer.toHexString(month.intValue()), 2, "0"));
		sum ^= month.intValue();

		Integer day = Integer.valueOf(cal.get(5));
		datasb.append(StringUtils.leftPad(Integer.toHexString(day.intValue()),
				2, "0"));
		sum ^= day.intValue();

		Integer hour = Integer.valueOf(cal.get(11));
		datasb.append(StringUtils.leftPad(Integer.toHexString(hour.intValue()),
				2, "0"));
		sum ^= hour.intValue();

		Integer minute = Integer.valueOf(cal.get(12));
		datasb.append(StringUtils.leftPad(
				Integer.toHexString(minute.intValue()), 2, "0"));
		sum ^= minute.intValue();

		datasb.append(StringUtils.leftPad(Integer.toHexString(sum), 2, "0"));

		return datasb.toString().toUpperCase();
	}

//	// 新增或更新
//	@PostMapping("/save")
//	@ApiOperation(value = "新增或更新", notes = "新增或更新")
//	public Result save(@RequestBody Receive receive){
//		return Result.success(receiveService.saveOrUpdate(receive));
//	}
//
//	// 根据ID删除
//	@GetMapping("/del/{id}")
//	@ApiOperation(value = "根据ID删除", notes = "根据ID删除")
//	public Result delete(@PathVariable Integer id){
//		return Result.success(receiveService.removeById(id));
//	}
//
//	// 根据IDS删除
//	@PostMapping("/del/batch")
//	@ApiOperation(value = "根据IDS删除", notes = "根据IDS删除")
//	public Result deleteBatch(@RequestBody List<Integer> ids){
//		return Result.success(receiveService.removeByIds(ids));
//	}
//
//	// 查询全部
//	@GetMapping("/findAll")
//	@ApiOperation(value = "查询全部", notes = "查询全部")
//	public Result findAll(){
//		return Result.success(receiveService.list());
//	}
//
//	// 根据ID查询一条记录
//	@GetMapping("/findOne")
//	@ApiOperation(value = "根据ID查询一条记录", notes = "根据ID查询一条记录")
//	public Result findOne(@RequestParam Integer id){
//		return Result.success(receiveService.getById(id));
//	}
//
//	// 分页查询
//	@GetMapping("/findPage")
//	@ApiOperation(value = "分页查询", notes = "分页查询")
//	public Result findPage(@RequestParam Integer pageNum,
//						   @RequestParam Integer pageSize,
//						   @RequestParam Long uid){
//		QueryWrapper<Receive> queryWrapper = new QueryWrapper<>();
//		if (uid != null) {
//			queryWrapper.eq("uid", uid);
//		}
//		queryWrapper.orderByDesc("createtime");
//		return  Result.success(receiveService.page(new Page<>(pageNum,pageSize),queryWrapper));
//	}

}
